const express = require('express');
const router = express.Router();
const Order = require('../models/Order');
const Cart = require('../models/Cart');
const Goods = require('../models/Goods');

// 创建订单
router.post('/auth/trade', auth, async (req, res) => {
  try {
    const { addressId } = req.body;
    
    // 获取用户地址信息
    const user = await User.findById(req.user.userId);
    const address = user.addresses.find(addr => addr._id.toString() === addressId);
    if (!address) {
      return res.status(404).json({
        code: 404,
        message: '地址不存在',
        data: null
      });
    }

    // 获取购物车中选中的商品
    const cartItems = await Cart.find({
      user: req.user.userId,
      selected: true
    }).populate('goods');

    if (cartItems.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '请选择要购买的商品',
        data: null
      });
    }

    // 计算订单总金额
    let totalAmount = 0;
    const items = cartItems.map(item => {
      const amount = item.goods.price * item.count;
      totalAmount += amount;
      return {
        goods: item.goods._id,
        count: item.count,
        price: item.goods.price,
        specs: item.specs,
        blessing: item.blessing
      };
    });

    // 生成订单号
    const orderNo = generateOrderNo();

    // 创建订单
    const order = await Order.create({
      user: req.user.userId,
      orderNo,
      items,
      totalAmount,
      address: {
        name: address.name,
        phone: address.phone,
        province: address.province,
        city: address.city,
        district: address.district,
        detail: address.detail
      }
    });

    // 清空购物车中已购买的商品
    await Cart.deleteMany({
      user: req.user.userId,
      selected: true
    });

    // 更新商品库存
    for (const item of cartItems) {
      await Goods.findByIdAndUpdate(item.goods._id, {
        $inc: { stock: -item.count, sales: item.count }
      });
    }

    res.json({
      code: 200,
      message: '创建订单成功',
      data: order
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '创建订单失败',
      data: null
    });
  }
});

// 获取订单列表
router.get('/auth/list', auth, async (req, res) => {
  try {
    const { status, page = 1, pageSize = 10 } = req.query;
    const query = { user: req.user.userId };
    
    if (status !== undefined) {
      query.status = parseInt(status);
    }

    const total = await Order.countDocuments(query);
    const orders = await Order.find(query)
      .populate('items.goods')
      .sort({ createdAt: -1 })
      .skip((page - 1) * pageSize)
      .limit(parseInt(pageSize));

    res.json({
      code: 200,
      message: '成功',
      data: {
        total,
        list: orders
      }
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取订单列表失败',
      data: null
    });
  }
});

// 获取订单详情
router.get('/auth/:id', auth, async (req, res) => {
  try {
    const order = await Order.findOne({
      _id: req.params.id,
      user: req.user.userId
    }).populate('items.goods');

    if (!order) {
      return res.status(404).json({
        code: 404,
        message: '订单不存在',
        data: null
      });
    }

    res.json({
      code: 200,
      message: '成功',
      data: order
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取订单详情失败',
      data: null
    });
  }
});

// 取消订单
router.get('/auth/cancelOrder/:id', auth, async (req, res) => {
  try {
    const order = await Order.findOne({
      _id: req.params.id,
      user: req.user.userId,
      status: 0
    });

    if (!order) {
      return res.status(404).json({
        code: 404,
        message: '订单不存在或无法取消',
        data: null
      });
    }

    // 恢复商品库存
    for (const item of order.items) {
      await Goods.findByIdAndUpdate(item.goods, {
        $inc: { stock: item.count, sales: -item.count }
      });
    }

    // 更新订单状态
    order.status = 4;
    order.cancelTime = new Date();
    await order.save();

    res.json({
      code: 200,
      message: '取消订单成功',
      data: order
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '取消订单失败',
      data: null
    });
  }
});

// 删除订单
router.delete('/auth/removeOrder/:id', auth, async (req, res) => {
  try {
    const order = await Order.findOneAndDelete({
      _id: req.params.id,
      user: req.user.userId,
      status: { $in: [3, 4] } // 只能删除已完成或已取消的订单
    });

    if (!order) {
      return res.status(404).json({
        code: 404,
        message: '订单不存在或无法删除',
        data: null
      });
    }

    res.json({
      code: 200,
      message: '删除订单成功',
      data: order
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '删除订单失败',
      data: null
    });
  }
});

// 确认收货
router.get('/auth/confirmReceive/:id', auth, async (req, res) => {
  try {
    const order = await Order.findOne({
      _id: req.params.id,
      user: req.user.userId,
      status: 2
    });

    if (!order) {
      return res.status(404).json({
        code: 404,
        message: '订单不存在或无法确认收货',
        data: null
      });
    }

    order.status = 3;
    order.completeTime = new Date();
    await order.save();

    res.json({
      code: 200,
      message: '确认收货成功',
      data: order
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '确认收货失败',
      data: null
    });
  }
});

// 获取订单支付信息
router.get('/auth/getPayInfo/:id', auth, async (req, res) => {
  try {
    const order = await Order.findOne({
      _id: req.params.id,
      user: req.user.userId,
      status: 0
    });

    if (!order) {
      return res.status(404).json({
        code: 404,
        message: '订单不存在或无法支付',
        data: null
      });
    }

    // 这里需要调用微信支付接口
    const payInfo = await createWxPay(order);

    res.json({
      code: 200,
      message: '成功',
      data: payInfo
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取支付信息失败',
      data: null
    });
  }
});

// 获取订单物流信息
router.get('/auth/getLogistics/:id', auth, async (req, res) => {
  try {
    const order = await Order.findOne({
      _id: req.params.id,
      user: req.user.userId,
      status: { $in: [1, 2] }
    });

    if (!order) {
      return res.status(404).json({
        code: 404,
        message: '订单不存在或无法查询物流',
        data: null
      });
    }

    // 这里需要调用物流查询接口
    const logistics = await queryLogistics(order.orderNo);

    res.json({
      code: 200,
      message: '成功',
      data: logistics
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取物流信息失败',
      data: null
    });
  }
});

// 生成订单号
function generateOrderNo() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
  return `${year}${month}${day}${random}`;
}

module.exports = router; 